package com.cy.hui_jie_dan.controller.chat;

import com.cy.hui_jie_dan.comon.result.Result;
import com.cy.hui_jie_dan.popj.dto.MarkReadRequest;
import com.cy.hui_jie_dan.popj.entity.ChatMessage;
import com.cy.hui_jie_dan.service.ChatMessageService;
import com.cy.hui_jie_dan.websocket.NettyWebSocketHandler;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/app/chat")
@Tag(name = "聊天接口", description = "处理聊天相关的请求")
public class ChatController {

    @Value("${file.upload-dir.images:${user.dir}/src/main/resources/templates/img}")
    private String imageUploadDir;

    @Autowired
    private ChatMessageService chatMessageService;

    @PostMapping("/send")
    @Operation(summary = "发送消息", description = "发送聊天消息")
    public Result<Void> sendMessage(@RequestBody ChatMessage message) {
        try {
            chatMessageService.saveMessage(message);
            // 通过WebSocket发送消息
            NettyWebSocketHandler.sendChatMessage(message.getToUserId().toString(), message);
            return Result.success();
        } catch (Exception e) {
            log.error("发送消息失败: {}", e.getMessage());
            return Result.error("发送消息失败");
        }
    }

    @GetMapping("/history")
    @Operation(summary = "获取聊天历史", description = "获取与指定用户的聊天历史记录")
    public Result<List<ChatMessage>> getChatHistory(
            @Parameter(description = "发送者ID") @RequestParam Integer fromUserId,
            @Parameter(description = "接收者ID") @RequestParam Integer toUserId,
            @Parameter(description = "返回记录数量限制") @RequestParam(defaultValue = "50") Integer limit,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime) {
        try {
            List<ChatMessage> messages = chatMessageService.getChatHistory(fromUserId, toUserId, limit, startTime);
            // 将消息标记为已读
            chatMessageService.markMessageAsRead(toUserId, fromUserId);
            return Result.success(messages);
        } catch (Exception e) {
            log.error("获取聊天历史失败: {}", e.getMessage());
            return Result.error("获取聊天历史失败");
        }
    }

    @GetMapping("/unread")
    @Operation(summary = "获取未读消息", description = "获取指定用户的未读消息")
    public Result<List<ChatMessage>> getUnreadMessages(
            @Parameter(description = "用户ID") @RequestParam Integer userId) {
        try {
            List<ChatMessage> messages = chatMessageService.getUnreadMessages(userId);
            return Result.success(messages);
        } catch (Exception e) {
            log.error("获取未读消息失败: {}", e.getMessage());
            return Result.error("获取未读消息失败");
        }
    }

    @PostMapping("/read")
    @Operation(summary = "标记消息已读", description = "将用户与指定联系人之间的所有未读消息标记为已读")
    public Result<Void> markMessageAsRead(@RequestBody MarkReadRequest request) {
        try {
            chatMessageService.markMessageAsRead(request.getUserId(), request.getContactId());
            return Result.success();
        } catch (Exception e) {
            log.error("标记消息已读失败: {}", e.getMessage());
            return Result.error("标记消息已读失败");
        }
    }

    @DeleteMapping("/message")
    @Operation(summary = "删除消息", description = "删除指定的聊天消息")
    public Result<Void> deleteMessage(
            @Parameter(description = "消息ID") @RequestParam String messageId,
            @Parameter(description = "用户ID") @RequestParam Integer userId) {
        try {
            chatMessageService.deleteMessage(messageId, userId);
            return Result.success();
        } catch (Exception e) {
            log.error("删除消息失败: {}", e.getMessage());
            return Result.error("删除消息失败");
        }
    }

    @GetMapping("/search")
    @Operation(summary = "搜索消息", description = "搜索聊天消息内容")
    public Result<List<ChatMessage>> searchMessages(
            @Parameter(description = "用户ID") @RequestParam Integer userId,
            @Parameter(description = "搜索关键词") @RequestParam String keyword) {
        try {
            List<ChatMessage> messages = chatMessageService.searchMessages(userId, keyword);
            return Result.success(messages);
        } catch (Exception e) {
            log.error("搜索消息失败: {}", e.getMessage());
            return Result.error("搜索消息失败");
        }
    }

    @GetMapping("/unread/count")
    @Operation(summary = "获取与指定联系人的未读消息数量", description = "获取用户与指定联系人的未读消息数量")
    public Result<Integer> getUnreadMessageCountWithUser(
            @Parameter(description = "用户ID") @RequestParam Integer userId,
            @Parameter(description = "联系人ID") @RequestParam Integer contactId) {
        try {
            int count = chatMessageService.getUnreadMessageCountWithUser(userId, contactId);
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取未读消息数量失败: {}", e.getMessage());
            return Result.error("获取未读消息数量失败");
        }
    }

    @GetMapping("/last-messages")
    @Operation(summary = "获取所有联系人的最后一条消息", description = "获取当前用户所有联系人的最后一条消息")
    public Result<List<ChatMessage>> getLastMessages(
            @Parameter(description = "用户ID") @RequestParam Integer userId) {
        try {
            List<ChatMessage> messages = chatMessageService.getLastMessages(userId);
            return Result.success(messages);
        } catch (Exception e) {
            log.error("获取最后消息列表失败: {}", e.getMessage());
            return Result.error("获取最后消息列表失败");
        }
    }

    @PostMapping("/upload/image")
    @Operation(summary = "上传图片", description = "上传聊天图片并返回URL")
    public Result<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("上传失败，请选择文件");
        }

        try {
            // 确保上传目录存在
            File uploadDir = new File(imageUploadDir);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String uniqueFileName = UUID.randomUUID().toString() + fileExtension;
            File destFile = new File(uploadDir, uniqueFileName);

            // 保存文件
            file.transferTo(destFile);

            // 构建可访问的URL（使用相对路径）
            String imageUrl = "/img/" + uniqueFileName;

            Map<String, String> response = new HashMap<>();
            response.put("imageUrl", imageUrl);
            log.info("图片上传成功: {}, 访问URL: {}", destFile.getAbsolutePath(), imageUrl);
            return Result.success(response);

        } catch (IOException e) {
            log.error("图片上传失败: {}", e.getMessage(), e);
            return Result.error("图片上传失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("图片上传时发生未知错误: {}", e.getMessage(), e);
            return Result.error("图片上传时发生未知错误");
        }
    }
}